package ar.com.ctrln.persistence.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

public abstract class AbstractHibernateDao<T extends Object> implements AbstractDao<T> {

	private Class<T> domainClass;
	
	@Autowired
	private SessionFactory sessionFactory;
	
	 public void setSessionFactory (SessionFactory sessionFactory){
	 this.sessionFactory = sessionFactory;
	 }
	
	 protected Session getSession() {
	 return sessionFactory.getCurrentSession();
	 }
	

	@SuppressWarnings("unchecked")
	private Class<T> getDomainClass() {
		if (domainClass == null) {
			ParameterizedType thisType = (ParameterizedType) getClass()
					.getGenericSuperclass();
			this.domainClass = (Class<T>) thisType.getActualTypeArguments()[0];

		}
		return domainClass;
	}

	private String getDomainClassName() {
		return getDomainClass().getName();
	}

	@Transactional
	public void save(T t) {
		getSession().save(t);
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly=true)
	public T get(Long id) {
		return (T) getSession().get(getDomainClass(), id);

	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly=true)
	public T load(Long id) {
		return (T) getSession().load(getDomainClass(), id);
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly=true)
	public List<T> getList() {
		Query q = getSession().createQuery("from " + getDomainClassName());
		return q.list();
	}

	@Transactional
	public void update(T t) {
		getSession().update(t);
	}

	@Transactional()
	public void delete(T t) {
		getSession().delete(t);
	}

	@Transactional
	public void deleteById(Long id) {
		getSession().delete(load(id));
	}

	@Transactional
	public void deleteAll() {
		Query q = getSession().createQuery("delete " + getDomainClassName());
		q.executeUpdate();
	}

	@Transactional(readOnly=true)
	public long count() {
		Query q = getSession().createQuery(
				"select count(*) from " + getDomainClassName());
		return (Long) q.uniqueResult();
	}


}
